package com.qsl;

import com.google.common.collect.Lists;
import com.google.common.primitives.Bytes;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.List;
import java.util.Optional;

/**
 * @Description:
 * @Author: 博客园@青石路
 * @CreateDate: 2023/5/6 9:51
 **/
public class Utf16leTest {
    public static void main(String[] args) throws IOException {
        // write();
        read();
    }

    public static void write() throws IOException {
        String str = "MD401|09996|沛嘉医疗-B                      |PEIJIA-B       |          560000|         5290670|      9.900|      9.390|      9.700|      9.340|      9.390|      0.000|           0|      0.000|           0|0       |16:18:22.000";
        File file = new File("D:/hello.txt");
        file.createNewFile();
        RandomAccessFile raf = new RandomAccessFile(file, "rw");
        FileChannel channel = raf.getChannel();
        ByteBuffer buffer = ByteBuffer.allocate(10240);
        List<Byte> lineBytes = Lists.newLinkedList();
        handleEncode(str, lineBytes);
        writeLine(Bytes.toArray(lineBytes), channel, buffer);
        buffer.clear();
    }

    public static void read() throws IOException {
        File file = new File("D:/2.txt");
        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-16LE"));
        String s = br.readLine();
        br.close();
        byte[] bytes = s.getBytes("UTF-16LE");
        System.out.println(bytes.length);
        System.out.println(new String(bytes, "GBK"));
    }

    private static void handleEncode(String data, List<Byte> lineBytes) throws UnsupportedEncodingException {
        String taskCharset = "GBK";
        String regex = "\\|";
        String[] dataArray = data.split(regex);
        String encodeData = dataArray[2];
        for (int i=0; i<2; i++) {
            lineBytes.addAll(Bytes.asList(dataArray[i].getBytes(taskCharset)));
            lineBytes.addAll(Bytes.asList("|".getBytes(taskCharset)));
        }
        char[] encodeDataArr = encodeData.toCharArray();
        for (char ch : encodeDataArr) {
            if (isChinese(ch)) {
                lineBytes.addAll(Bytes.asList(String.valueOf(ch).getBytes("UTF-16LE")));
            } else {
                lineBytes.addAll(Bytes.asList(String.valueOf(ch).getBytes(taskCharset)));
            }
        }
        for (int i=3; i<dataArray.length; i++) {
            lineBytes.addAll(Bytes.asList("|".getBytes(taskCharset)));
            lineBytes.addAll(Bytes.asList(dataArray[i].getBytes(taskCharset)));
        }
        if (data.endsWith("|")) {
            lineBytes.addAll(Bytes.asList("|".getBytes(taskCharset)));
        }
    }

    private static int writeLine(byte[] bytes, FileChannel fc, ByteBuffer buffer) throws IOException {
        ByteBuffer byteBuffer = Optional.ofNullable(buffer).orElse(ByteBuffer.allocate(10240));
        buffer.clear();
        int capacity = byteBuffer.capacity();
        int from = 0;

        int len = capacity;
        while(from < bytes.length) {
            if((len+from) > bytes.length) {
                len = bytes.length - from;
            }
            byteBuffer.clear();
            byteBuffer.put(ByteBuffer.wrap(bytes, from, len));
            byteBuffer.flip();
            fc.write(byteBuffer);
            from += len;
        }
        return from;
    }

    public static boolean isChinese(char c) {
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
                || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
                || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
            return true;
        }
        return false;
    }
}
